package com.dd.logistics.controller;

import com.dd.logistics.common.Result;
import com.dd.logistics.entity.User;
import com.dd.logistics.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result<User> login(@RequestParam String username, @RequestParam String password) {
        try {
            if (username == null || username.trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }
            if (password == null || password.trim().isEmpty()) {
                return Result.error("密码不能为空");
            }
            
            User user = userService.login(username.trim(), password.trim());
            if (user != null) {
                user.setPassword(null);
                return Result.success("登录成功", user);
            }
            return Result.error("用户名或密码错误");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("登录失败：" + e.getMessage());
        }
    }

    @PostMapping("/register")
    public Result<Boolean> register(@RequestBody User user) {
        try {
            if (user.getUsername() == null || user.getPassword() == null) {
                return Result.error("用户名和密码不能为空");
            }
            boolean success = userService.save(user);
            return success ? Result.success("注册成功", true) : Result.error("注册失败");
        } catch (Exception e) {
            return Result.error("注册失败：" + e.getMessage());
        }
    }
    
    @PutMapping("/update")
    public Result<Boolean> updateUser(@RequestBody User user) {
        try {
            if (user.getId() == null) {
                return Result.error("用户ID不能为空");
            }
            boolean success = userService.updateById(user);
            return success ? Result.success("更新成功", true) : Result.error("更新失败");
        } catch (Exception e) {
            return Result.error("更新失败：" + e.getMessage());
        }
    }
} 